﻿using KnifeZ.Byeol.Models;
using KnifeZ.Unity.EasyService;
using KnifeZ.Unity.Helper;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KnifeZ.Byeol.Services
{
    public class TimingJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            using DataContext db = new DataContext(AppSettings.DefaultConnectString);
            var item = db.Set<ByeolTask>().Where(x => x.ID == (long)context.JobDetail.JobDataMap.Get("itemID")).FirstOrDefault();

            string result = "";
            string errorMsg = "";
            if (item.IsInterrupt)
            {
                result = "任务已中断，并未执行";

            }
            SimpleEmail simpleEmail = new SimpleEmail();
            SimpleEmail.UserEmailAddress = "指定邮箱";
            SimpleEmail.UseDisplayName = "ByeolAutoMail";
            SimpleEmail.password = "授权码";
            //当前时间大于创建时间
            if (!item.IsInterrupt && DateTime.Now > item.CreateTime)
            {
                try
                {
                    //item.Headers  暂时无用
                    Dictionary<string, string> postData = new Dictionary<string, string>();
                    if (!string.IsNullOrEmpty(item.AskParams))
                    {
                        postData = JsonConvert.DeserializeObject<Dictionary<string, string>>(item.AskParams);
                    }
                    result = await APIHelper.CallAPI(item.AskApi, item.AskMethodType, postData);
                    result = System.Text.RegularExpressions.Regex.Unescape(result);
                }
                catch (Exception ex)
                {
                    errorMsg = ex.Message + ex.StackTrace;
                }
                db.Update(item);
                db.Add(new ByeolTaskRecord()
                {
                    TaskID = item.TaskID,
                    ExecuteResult = result,
                    ErrorMessage = errorMsg,
                    ExecuteTime = DateTime.Now
                });
                db.SaveChanges();
                if (item.IsEmail)
                {
                    foreach (var email in item.EmailAddress.Split(','))
                    {

                        simpleEmail.SendMailByQQ("Byeol定时任务监控", result, email);
                    }
                }
            }
        }
    }
}
